package com.pixiv.servlet.RegisterServlet;

import com.pixiv.MysqlDAO.UserLoginDAO;
import com.pixiv.tools.SendPrintWriterPacket;
import com.pixiv.user.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;

@WebServlet("/RegisterUserServlet")
public class RegisterUserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        String type = req.getParameter("appType");
        try {
            Class<?> c = this.getClass();
            Method me = c.getMethod("Service_" + type, HttpServletRequest.class, HttpServletResponse.class);
            me.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //初始化进入注册界面
    public void Service_InitGotoRegister(HttpServletRequest req, HttpServletResponse resp)
    {
        resp.setContentType("application/json;charset=utf-8");
        SendPrintWriterPacket.sendFlag(resp,1);
    }

    //获得注册请求
    public void Service_SendRegisterPacket(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        resp.setContentType("application/json;charset=utf-8");
        String name = req.getParameter("User");
        String code = req.getParameter("Code");
        HttpSession hs = req.getSession();

        User u = UserLoginDAO.getUserByLoginParameter(name);

        if (u == null)
        {
            String Pwd = req.getParameter("PWD");

            if (!hs.getAttribute("Register_getCode").equals(code) )
            {
                SendPrintWriterPacket.sendFlag(resp,1);
            }else
            {
                UserLoginDAO.RegisterUserByLoginParameter(name,Pwd);
                SendPrintWriterPacket.sendFlag(resp,2);
            }

        }else
        {
            SendPrintWriterPacket.sendFlag(resp,0);
        }


    }
}
